package xyz.coolcsm.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.Payload;
import xyz.coolcsm.security.entity.Resource;
import xyz.coolcsm.security.entity.SysUser;
import xyz.coolcsm.security.service.RedisService;
import xyz.coolcsm.security.service.ResourceService;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
/**
 * @author 什锦
 * @since 2021-06-1
 */

@RestController
public class ResourceController {

    @Autowired
    ResourceService resourceService;

    @Autowired
    private RsaKeyProperties prop;

    @Autowired
    private RedisService redisService;



    @PreAuthorize("hasAuthority('query_info')")
    //资源分页展示
    @GetMapping("/api/resource/{limit}/{page}")
    public JsonResult questionListPage(@PathVariable("page") int page, @PathVariable("limit") int limit){
        if (page < 1){
            page = 1;
        }
        String key = "redis:resource:" +page;
        Object object = redisService.get(key);
        if (object == null){
            Page<Resource> pageParam = new Page<>(page, limit);
            resourceService.page(pageParam,new QueryWrapper<Resource>().orderByDesc("create_time"));
            redisService.set(key,pageParam,60*60);
            return ResultTool.success(pageParam);
        }
        Page<Resource> resourcePage = (Page<Resource>) object;
        return ResultTool.success(resourcePage);
    }

    //根据关键字查找资源
    @GetMapping("/api/resource/{limit}/{page}/{keyWord}")
    public JsonResult resourceListPageByKeyWords(@PathVariable("page") int page, @PathVariable("limit") int limit,
                                                 @PathVariable("keyWord") String keyWord){
        if (page < 1) {
            page = 1;
        }
        String key = "redis:resource:" +keyWord+page;
        Object object = redisService.get(key);
        if (object == null){
            Page<Resource> pageParam = new Page<>(page, limit);
            resourceService.page(pageParam,new QueryWrapper<Resource>().like("ddesc",keyWord).orderByDesc("create_time"));
            redisService.set(key,pageParam,60*60);
            return ResultTool.success(pageParam);
        }
        Page<Resource> resourcePage = (Page<Resource>) object;
        return ResultTool.success(resourcePage);
    }

    //个人资源分类
    @PostMapping("/api/resource/{limit}/{page}")
    public JsonResult resourceListPageByuser(HttpServletRequest request, @PathVariable("page") int page, @PathVariable("limit") int limit){
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        SysUser user = payload.getUserInfo();
        Page<Resource> pageParam = new Page<>(page, limit);
        resourceService.page(pageParam,new QueryWrapper<Resource>().eq("dname",user.getNickName()).orderByDesc("create_time"));
        return ResultTool.success(pageParam);
    }

    @DeleteMapping("/api/resource/delete/{id}")
    public JsonResult deleteResource(HttpServletRequest request,@PathVariable("id") int id){
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        SysUser user = payload.getUserInfo();
        Resource resource = new Resource();
        resource.setId(String.valueOf(id));
        boolean remove = resourceService.remove(new QueryWrapper<Resource>().eq("dname", user.getNickName()).eq("id", id));
        if (remove == false){
            return ResultTool.fail();
        }
        for (int i = 1;i<100;i++){
            String key = "redis:resource:" +i;
            redisService.del(key);
        }
        return ResultTool.success();
    }

    @PostMapping("/api/resource/add")
    public JsonResult addResource(HttpServletRequest request,@RequestBody Resource resource){
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        SysUser user = payload.getUserInfo();
        String s = resource.getTitle() + ":" + resource.getDdesc();
        resource.setDdesc(s);
        resource.setDname(user.getNickName());
        boolean b = resourceService.saveOrUpdate(resource);

        if (b == false){
            return ResultTool.fail();
        }

        for (int i = 1;i<100;i++){
            String key = "redis:resource:" +i;
            redisService.del(key);
        }

        return ResultTool.success();
    }

}
